import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {AuthorizationService} from './authorization.service';
import {NzMessageService} from 'ng-zorro-antd';
import {isNullOrUndefined} from 'util';

@Component({
    selector: 'kylin-authorization-list',
    templateUrl: './authorization-list.component.html',
    styleUrls: ['./authorization-list.component.less']
})
export class AuthorizationListComponent implements OnInit {
    id: any;
    nodes: any;
    selectKeys;
    permissionCode = [];
    constructor(private route: ActivatedRoute,
                private authorizationService: AuthorizationService,
                private message: NzMessageService,
                private router: Router) {
        this.route.queryParams.subscribe((params) => {
            this.id = params.id
        })
    }

    ngOnInit() {
        this.getRolePermissions();
    }

    // 获取角色权限
    getRolePermissions() {
        this.authorizationService.getPermissions(this.id)
            .then(rep => {
                if (rep.resp_code === '10000') {
                    console.log(rep.data);
                    this.nodes = rep.data.nodes;
                } else {

                }
            })
            .catch(() => {

            })
    }

    update() {
        let params;
        this.getCheckCode(this.nodes, this.permissionCode).then(data => {
            params = {
                roleId: this.id,
                permissionIds: data
            };
            this.authorizationService.subUpDate(this.id, data).then(rep => {
                if (rep.resp_code === '10000') {
                    this.message.success('权限分配成功');
                    this.back()
                } else {
                    this.message.error(rep.resp_msg)
                }
            })
                .catch(() => {
                    this.message.error('权限分配失败')
                })
        });
    }

    private getCheckCode(nodes, permissionCode) {
        return  new Promise((resolve) => {
            nodes.forEach(value => {
                if (value.checked || value.halfChecked) {
                    permissionCode.push(value.key);
                }
                if (!isNullOrUndefined(value.children)) {
                    this.getCheckCode(value.children, permissionCode);
                }
            });
            resolve(permissionCode)
        })
    }

    back() {
        this.router.navigate(['home/identity-managment/role-managment'])
    }

}
